#!/usr/bin/python
# coding=gbk

import sys

class msg_class:
    def __init__(self, m, f):
        self.msgstr = m
        self.files = f

def print_usage():
    print("Usage: import.py [po file]")

def replace(FileName, LineNum, OldStr, NewStr):
    result = False
    needWrite = False
    text = ''
    count = 1
    FILE = open(FileName, 'r')
    line = FILE.readline()
    while line:
        if count == LineNum:
            if line.find(OldStr) == -1:
                break;
            line = line.replace(OldStr, NewStr, 1)
            needWrite = True
        text += line
        count += 1
        line = FILE.readline()
    FILE.close()
    if needWrite:
        line += '\n'
        FILE = open(FileName, 'w')
        FILE.write(text)
        FILE.close()
        result = True
        
    return result

def read_po(FileName):
    msg = {}
    msgid = ''
    msgstr = ''
    files = {}
    
    PO = open(FileName, 'r')
    line = PO.readline()
    while line:
        line = line.strip().decode("utf-8").encode("gbk")
        if line[0:3] == '#: ':
            for pair in line[3:].split():
                (n, l) = pair.split(':') #split name and line num
                n = n.replace('\\', '/') #use unix file format
                if not files.has_key(n):
                    files[n] = []
                files[n].append(l)
        elif line[0:6] == 'msgid ':
            msgid =  line[6:]
        elif line[0:7] == 'msgstr ':
            msgstr = line[7:]
        
        if msgstr != '':
            if msgstr != '""':
                msg[msgid] = msg_class(msgstr, files)
            msgid = ''
            msgstr = ''
            files = {}
            
        line = PO.readline()
    #end while
    PO.close()
    return msg

#start from here
if len(sys.argv) != 2 :
    print_usage()
    sys.exit()

errorOccur = False

messages = read_po(sys.argv[1])
specials = read_po('special.po')

for id, msg in messages.items():
    for filename, lineNums in msg.files.items():
        for lineNum in lineNums:
            newstr = msg.msgstr
            if specials.has_key(id) \
              and specials[id].files.has_key(filename) \
              and lineNum in specials[id].files[filename]:
                newstr = specials[id].msgstr
            if not replace(FileName = filename, LineNum = int(lineNum), OldStr = id, NewStr = newstr):
                print("Error:")
                errorOccur = True
            print("%s %s:\n%s\n%s\n" % (filename, lineNum, id, msg.msgstr))

if errorOccur:
    print 'Warning: something wrong happened!!'

